#!/usr/bin/env python

# Written for Python 2.5.2
# May 2009

import sys, os, time
from numpy import *
from numpy.linalg import svd
import cProfile, pstats
import traceback # for printing traceback
import smtplib # for emailing
from memorymonitor import MemoryMonitor

def svd_est(nrows,ncols):
	try:
		mm=random.randn(nrows,ncols)
		print 'Processing SVD of a %d x %d matrix started ' % (nrows, ncols)
		print str(time.strftime("%a %d %b %Y %I:%M:%S %p"))	
		t1 = time.time()
		bb=svd(mm)
		t2 = time.time()
		print 'For a %d x %d matrix it took %0.3f sec' % (nrows, ncols, t2-t1)
	except:
		#following line does not print the exception trace - figure out why sys.exc_info()
		print 'ERROR - exception caught in svd-est:\n' + traceback.format_exc()
	finally:
		return t2-t1
		
# run standalone
if __name__ == "__main__":
	nargs=len(sys.argv)
	
	if nargs<3:
		print 'Usage: '+sys.argv[0]+' nrows ncols'
		sys.exit(-1)
	
	#ram_size = raw_input('what is the size of RAM on this machine?')
	nrows,ncols=map(int,sys.argv[1:])

	memory_mon = MemoryMonitor('baseline')
	used_memory = memory_mon.usage()
	print 'Free RAM on this system required should be: %d' % used_memory*2 
	tocont = 'y'
	tocont = raw_input('Do you wish to continue[y]?')
	toemail = 'n'
	toemail = raw_input('Do you wish to be emailed when the job is completed (requires entering server, address and text)[n]?')
	if (tocont == 'y'):
		svd_est(nrows,ncols)
		
		# if we want to profile the CPU usage but we know who takes the most time:
		#ncalls  tottime  percall  cumtime  percall filename:lineno(function)
		#   2     39.213   19.606   39.213   19.606 {numpy.linalg.lapack_lite.dgesdd}
	
		#cProfile.run('svd_est()')
		if (toemail == 'y'):
			# gather inputs for emailing
			mailserver = raw_input('Name of your email forwarding server?')
			youremail = raw_input('Your email address?')
			emailsubject = 'SVD run completed!'
			mail(mailserver, youremail, youremail, emailsubject, emailsubject)
	
def mail(serverURL=None, sender='', to='', subject='', text=''):
	"""
	Usage:
	mail('somemailserver.com', 'me@eg.com', 'one@eg.com', 'test', 'body')
	"""
	headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
	message = headers + text
	mailServer = smtplib.SMTP(serverURL)
	mailServer.sendmail(sender, to, message)
	mailServer.quit()
